package com.jie.netty.im.tactics.impl;

import com.jie.constants.ChannelAttrKey;
import com.jie.constants.IMRedisKey;
import com.jie.netty.im.UserChannelCtxMap;
import com.jie.netty.im.tactics.DisconnectionHandler;
import com.jie.netty.model.IMSendInfo;
import com.jie.netty.type.IMCmdType;
import com.jie.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * 房间信息的断开处理类
 */
@Slf4j
public class RoomDisconnectionHandler implements DisconnectionHandler {

    @Override
    public void handleDisconnection(ChannelHandlerContext ctx) {
        AttributeKey<String> userIdAttr = AttributeKey.valueOf(ChannelAttrKey.USER_NAME);
        String username = ctx.channel().attr(userIdAttr).get();
        AttributeKey<String> roomAttr = AttributeKey.valueOf(ChannelAttrKey.ROOM_ID);
        String roomId = ctx.channel().attr(roomAttr).get();
        List<ChannelHandlerContext> groupChannelCtx = UserChannelCtxMap.getGroupChannelCtx(roomId);
        // 这里对大家发布一个消息就是用户下线了
        RedisTemplate<String, Object> redisTemplate = SpringContextHolder.getBean("redisTemplate");
        String key = String.join(":", IMRedisKey.IM_ROOM_USER_ID, username, roomId);
        IMSendInfo<Object> sendInfo = new IMSendInfo<>();
        sendInfo.setCmd(IMCmdType.TEAM_OFFLINE_MESSAGE.code());
        sendInfo.setData("用户" + username + "下线了");
        if (groupChannelCtx!= null) {
            for (ChannelHandlerContext channelCtx : groupChannelCtx) {
                channelCtx.channel().writeAndFlush(sendInfo);
            }
        }
        log.info("房间连接断开,用户:{},房间号:{}", username, roomId);
        redisTemplate.delete(key);
    }
}
